/**     
 * @{#} ModHashArithmetic.java Create on 2011-7-22 上午10:40:00     
 *     
 * Copyright (c) 2011 by xiaofeng.zhouxf     
 */
package com.sefer.memcached.arithmetic;

/**
 * @author <a href="mailto:xiaofeng.zhouxf83@gmail.com">xiaofeng.zhouxf</a>
 * @version 1.0
 */
public class ModHashArithmetic implements HashArithmetic {
	private final int primeNumberArray[] = { 2, 3, 5, 7, 13, 17, 19, 31 };

	@Override
	public int calculate(Object key, int totalNodeNumber) {
		// FIXME 该算法有些问题
		int hashCode = key.hashCode();
		int tempHashCode = (hashCode < 0 ? hashCode * -1 : hashCode);
		int tempHashCode2 = tempHashCode;
		int index = 0;
		for (int i = 0; i < 8; i++) {
			tempHashCode = (tempHashCode2 % ((1 << primeNumberArray[i]) - 1));
			if (tempHashCode > totalNodeNumber) {
				continue;
			}
			index = tempHashCode % totalNodeNumber;
			break;
		}

		return index;

	}

	public static void main(String[] args) {
		String test = "test";
		for (int i = 0; i < 100; i++)
			System.out.println("index: "
					+ new ModHashArithmetic().calculate(new String("test" + i),
							2));

	}
}
